//
//  HNHandleCourseSelectAddressView.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/8.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "HNHandleCourseSelectAddressView.h"

@implementation HNHandleCourseSelectAddressView
{
    
    __weak IBOutlet UIButton *_blackView;
    __weak IBOutlet UIView *_contentView;
    __weak IBOutlet NSLayoutConstraint *_contentViewBottom;
    __weak IBOutlet UIPickerView *_pickerView;
    NSArray *_regionArr;
    void (^_CallBack)(NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSString *);
    
    NSInteger _proviceIndex;
    NSInteger _cityIndex;
    NSInteger _areaIndex;
}

+ (instancetype)handleCourseSelectAddressViewWithRegionArr:(NSArray *)regionArr CallBack:(void (^)(NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSString *))callBack {
    
    return [[self alloc] initWithhandleCourseSelectAddressViewWithRegionArr:regionArr CallBack:callBack];
}

- (instancetype)initWithhandleCourseSelectAddressViewWithRegionArr:(NSArray *)regionArr CallBack:(void (^)(NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSNumber *, NSString *, NSString *))callBack {
    
    self = [[NSBundle mainBundle] loadNibNamed:[HNHandleCourseSelectAddressView description] owner:nil options:nil][0];
    if (self) {
        
        _regionArr = regionArr;
        _CallBack = callBack;
        _blackView.alpha = 0;
        _contentViewBottom.constant = -250;
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        
        self.frame = [UIScreen mainScreen].bounds;
        
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        
        
        [UIView animateWithDuration:0.3 animations:^{
            _blackView.alpha = 1;
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5f initialSpringVelocity:0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
                _contentViewBottom.constant = 0;
                [self layoutIfNeeded];
            } completion:^(BOOL finished) {
                
            }];
        }];
        
    }
    return self;
}


- (IBAction)Done:(id)sender {
    
    regionProvice *proviceObj = _regionArr[_proviceIndex];
    regionCity *cityObj = proviceObj.cities[_cityIndex];
    regionArea *areaObj = cityObj.areas[_areaIndex];
    
    _CallBack ? _CallBack (proviceObj.provincename,
                           proviceObj.provinceid,
                           cityObj.cityname,
                           cityObj.cityid,
                           areaObj.areaname,
                           areaObj.areaid,
                           [NSString stringWithFormat:@"%@%@%@", proviceObj.provincename, cityObj.cityname, areaObj.areaname],
                           [NSString stringWithFormat:@"%@-%@-%@", [proviceObj.provinceid stringValue], [cityObj.cityid stringValue], [areaObj.areaid stringValue]]
                           ) : nil;
    [self dissmiss:nil];
}


- (IBAction)dissmiss:(id)sender {
    
    
    
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5f initialSpringVelocity:0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
        _contentViewBottom.constant = -250;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.3 animations:^{
            _blackView.alpha = 0;
        } completion:^(BOOL finished) {
            
            [self removeFromSuperview];
        }];
    }];
}



#pragma mark - pickerView delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (component == 0) {
        
        // 省
        return _regionArr.count;
        
    } else if (component == 1) {
        
        // 市
        regionProvice *proviceObj = _regionArr[_proviceIndex];
        return proviceObj.cities.count;
        
    } else {
        
        // 区
        regionProvice *proviceObj = _regionArr[_proviceIndex];
        regionCity *cityObj = proviceObj.cities[_cityIndex];
        return cityObj.areas.count;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return [UIScreen mainScreen].bounds.size.width / 3.0;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    
    return 44.f;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (component == 0) {
        
        // 省
        regionProvice *proviceObj = _regionArr[row];
        return proviceObj.provincename;
        
    } else if (component == 1) {
        
        // 市
        regionProvice *proviceObj = _regionArr[_proviceIndex];
        regionCity *cityObj = proviceObj.cities[row];
        return cityObj.cityname;
        
    } else {
        
        // 区
        regionProvice *proviceObj = _regionArr[_proviceIndex];
        regionCity *cityObj = proviceObj.cities[_cityIndex];
        regionArea *areaObj = cityObj.areas[row];
        return areaObj.areaname;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) {
        
        _proviceIndex = row;
        _cityIndex = 0;
        _areaIndex = 0;
        
    } else if (component == 1) {
        
        _cityIndex = row;
        _areaIndex = 0;
        
    } else {
        
        _areaIndex = row;
    }
    [_pickerView reloadAllComponents];
}














#pragma mark - 类方法：地区
/** 获取所有的地区 */
+ (void)regionArr:(void (^)(NSArray *Arr))callBack {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        callBack ? callBack ([self creatRegion]) : nil;
    });
}


+ (NSArray *)creatRegion {
    
    
    NSData *proviceJSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shengfen" ofType:@"json"]];
    NSArray *proviceDataArray = [NSJSONSerialization JSONObjectWithData:proviceJSONData options:NSJSONReadingAllowFragments error:nil];
    NSMutableArray *proviceArr = [NSMutableArray array];
    [proviceDataArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [proviceArr addObject:[[regionProvice alloc] initWithDict:obj]];
    }];
    
    NSData *cityJSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"allcity" ofType:@"json"]];
    NSArray *cityDataArray = [NSJSONSerialization JSONObjectWithData:cityJSONData options:NSJSONReadingAllowFragments error:nil];
    NSMutableArray *cityArr = [NSMutableArray array];
    [cityDataArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [cityArr addObject:[[regionCity alloc] initWithDict:obj]];
    }];
    
    NSData *areaJSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"allarea" ofType:@"json"]];
    NSArray *areaDataArray = [NSJSONSerialization JSONObjectWithData:areaJSONData options:NSJSONReadingAllowFragments error:nil];
    NSMutableArray *areaArr = [NSMutableArray array];
    [areaDataArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [areaArr addObject:[[regionArea alloc] initWithDict:obj]];
    }];
    
    // 区数据放在城市的位置
    [areaArr enumerateObjectsUsingBlock:^(regionArea * _Nonnull areaObj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [cityArr enumerateObjectsUsingBlock:^(regionCity * _Nonnull cityObj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            // 如果区的cityid 等于这个城市id，就加进这个城市的区数组里
            if ([areaObj.cityid isEqualToNumber:cityObj.cityid]) {
                
                [cityObj.areas addObject:areaObj];
                *stop = YES;
            }
        }];
    }];
    
    // 城市放进省位置
    [cityArr enumerateObjectsUsingBlock:^(regionCity * _Nonnull cityObj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [proviceArr enumerateObjectsUsingBlock:^(regionProvice * _Nonnull proviceObj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([cityObj.provinceid isEqualToNumber:proviceObj.provinceid]) {
                
                [proviceObj.cities addObject:cityObj];
                *stop = YES;
            }
        }];
    }];
    

    // 补全直辖市没有区的情况
    for (regionProvice *proviceObj in proviceArr) {
        
        for (regionCity *cityObj in proviceObj.cities) {
            
            if (cityObj.areas == nil || cityObj.areas.count == 0) {
                
                regionArea *areaObj = [[regionArea alloc] init];
                areaObj.cityid = cityObj.cityid;
                areaObj.areaid = @0;
                areaObj.areaname = @"市辖区";
                [cityObj.areas addObject:areaObj];
            }
        }
        
    }
    
    return [proviceArr copy];
}
@end

















//省
@implementation regionProvice

- (instancetype)initWithDict:(NSDictionary *)Dict
{
    self = [super init];
    if (self)
    {
        [self setValuesForKeysWithDictionary:Dict];
    }
    return self;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{};
- (NSMutableArray *)cities { if (!_cities) { _cities = [NSMutableArray array]; } return _cities; }
@end


//城
@implementation regionCity

- (instancetype)initWithDict:(NSDictionary *)Dict
{
    self = [super init];
    if (self)
    {
        [self setValuesForKeysWithDictionary:Dict];
    }
    return self;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{};
- (NSMutableArray *)areas { if (!_areas) { _areas = [NSMutableArray array]; } return _areas; }
@end

//区
@implementation regionArea
- (instancetype)initWithDict:(NSDictionary *)Dict
{
    self = [super init];
    if (self)
    {
        [self setValuesForKeysWithDictionary:Dict];
    }
    return self;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{};
@end
